/**
 * MasicOutput
 * <p/>
 * User: joakimd
 * Date: 2013-03-11
 * Time: 11:37
 */
package org.dru.masic {
import flash.events.Event;

public final class MasicOutput extends MasicPort {
    private var _targets: Vector.<MasicInput>;

    public function MasicOutput(parent: MasicComponent, name: String, stereo: Boolean) {
        super(parent, name, stereo);
        _targets = new Vector.<MasicInput>();
    }

    internal function get targets(): Vector.<MasicInput> {
        return _targets;
    }

    public function get numTargets(): int {
        return targets.length;
    }

    public function getTargetAt(index: int): MasicInput {
        return targets[index];
    }

    public function getTargetIndex(target: MasicInput): int {
        return targets.indexOf(target);
    }

    public function addTarget(target: MasicInput): void {
        if (getTargetIndex(target) == -1) {
            targets.push(target);
            target.addSource(this);
            dispatchEvent(new Event(Event.CHANGE));
        }
    }

    public function removeTarget(target: MasicInput): void {
        const index: int = getTargetIndex(target);
        if (index != -1) {
            removeTargetAt(index);
        }
    }

    public function removeAllTargets(): void {
        for (var index: int = numTargets; --index >= 0;) {
            removeTargetAt(index);
        }
    }

    private function removeTargetAt(index: int): void {
        const target: MasicInput = targets.splice(index, 1)[0];
        target.removeSource(this);
        dispatchEvent(new Event(Event.CHANGE));
    }
}
}
